const Router = require('koa-router')
const { TokenValidator, NotEmptyValidator } = require('../../validator/validator')
const User = require('../../../db/model/user')
const { generateToken } = require('../../../core/util')
const WXManager = require('../../service/wx')
const Auth = require('../../../middlewares/auth')

const router = new Router({ prefix: '/v1/token'})


// post接受三个参数：account, type, *secret, 
// TokenValidator验证指定type的account是否存在以及对应的secret是否正确
// 最终返回生成的token
router.post('/', async (ctx, next) => {
  const v = await new TokenValidator().validate(ctx)
  
  const type = v.get('body.type')
  const account = v.get('body.account')
  const secret = v.get('body.secret')

  let token

  switch (type) {
    case 'USER_EMAIL':
      token = await emailLogin(account, secret)
      break;
    case 'USER_MINI_PROGRAM':
      token = await WXManager.codeToToken(account)
      break;
    default :
      throw new Error('该type处理函数未定义')
  }
  
  ctx.body = {
    token
  }

  await next()
})


// 验证前端传入的token是否合法
router.post('/verify', async (ctx) => {
  const v = await new NotEmptyValidator().validate(ctx)
  const token = v.get('body.token')
  const result = Auth.verifyToken(token)
  ctx.body = {
    result
  }
})



async function emailLogin(account, secret) {
  const user = await User.validateEmailLogin(account, secret)
  return generateToken(user.id, 8)
}

module.exports = router